package com.yitao.cms.service.order;

import com.querydsl.core.types.Order;
import com.querydsl.core.types.OrderSpecifier;
import com.skipper.base.bean.PagedInput;
import com.skipper.base.bean.PagedOutput;
import com.skipper.base.data.querydsl.PredicateBuilder;
import com.skipper.base.service.GenericEntityService;
import com.yitao.client.constant.PackageEnum;
import com.yitao.client.dto.order.OrderDeliveryPackageInfoDto;
import com.yitao.client.model.order.OrderDeliveryPackageInfoModel;
import com.yitao.client.model.order.QOrderDeliveryPackageInfoModel;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import java.util.List;

@Service
public class CmsOrderDeliveryPackageInfoService extends GenericEntityService<OrderDeliveryPackageInfoModel, OrderDeliveryPackageInfoDto, QOrderDeliveryPackageInfoModel> {
    public CmsOrderDeliveryPackageInfoService(EntityManager entityManager) {
        super(entityManager);
    }

    /**
     * 根据DTO查询
     */
    public PagedOutput<OrderDeliveryPackageInfoModel> getPagedOutputByBean(OrderDeliveryPackageInfoDto orderDeliveryPackageInfoDto, PagedInput pagedInput) {
        PredicateBuilder predicateBuilder = PredicateBuilder.conjunction().
                ifNotNullThenAnd(orderDeliveryPackageInfoDto.getPackageStatus(), () -> Q.packageStatus.eq(orderDeliveryPackageInfoDto.getPackageStatus())).
                ifNotNullThenAnd(orderDeliveryPackageInfoDto.getShopId(), () -> Q.shopId.eq(orderDeliveryPackageInfoDto.getShopId()));
        return repository.pagingList(predicateBuilder.get(), pagedInput, new OrderSpecifier<>(Order.DESC, Q.createTime));
    }

    @Transactional
    public OrderDeliveryPackageInfoModel save(OrderDeliveryPackageInfoModel orderDeliveryPackageInfoModel) {
        return repository.save(orderDeliveryPackageInfoModel);
    }

    //根据包裹ID查询包裹
    public OrderDeliveryPackageInfoModel getOrderDeliveryPackageInfoModel(Long id) {
        return queryFactory.select(Q).from(Q).where(Q.id.eq(id)).fetchOne();
    }

    public List<OrderDeliveryPackageInfoModel> getOrderDeliveryPackageInfoModelByOrderId(Long orderId) {
        return queryFactory.select(Q).from(Q).where(Q.orderId.eq(orderId).and(Q.packageStatus.in(PackageEnum.PackageStatusEnum.SHIPPED.getCode(), PackageEnum.PackageStatusEnum.HAVE_BEEN_SIGNED.getCode()))).fetch();
    }

    public OrderDeliveryPackageInfoModel getOrderDeliveryPackageInfoModelByPackageCode(String packageCode) {
        return queryFactory.select(Q).from(Q).where(Q.packageCode.eq(packageCode)).fetchOne();
    }
}
